<?php

namespace app\admin\controller\task;

use app\admin\model\shop\Paidan;
use app\admin\model\store\Order;
use think\facade\Db;
use Throwable;
use app\common\controller\Backend;

/**
 * 提交管理
 */
class Log extends Backend
{
    /**
     * Log模型对象
     * @var object
     * @phpstan-var \app\admin\model\task\Log
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected array $withJoinTable = ['shopUser', 'taskTask'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\task\Log();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['shopUser' => ['nickname'], 'taskTask' => ['name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $orderModel = new Order();
                $res = $orderModel->endOrder($row->string);
                if(!isset($res['status']) || !$res['status']){
                    $this->model->rollback();
                    $this->error('订单号错误，请确认订单号');
                }
                $result = $row->save($data);
                if (isset($data['status']) && $data['status'] == 1) {
                    $config = Db::name('task_task')->where('id',$row['task_task_id'])->find();
                    $userfind = Db::name('shop_user')->where('id', $row['shop_user_id'])->find();
                    if($userfind['pstatus'] == 1 && $userfind['level_id'] == 1){
                        if(isset($config['number1']) && $config['number1'] != '' &&  $config['number1'] != 0){
                            $model = new Paidan();
                            $res = $model->change($row['shop_user_id'],$model::TYPE_VIDEO,$config['number1'],$row['id']);
                        }

                    }elseif ($userfind['pstatus'] == 1 && $userfind['level_id'] == 2){
                        if(isset($config['number2']) && $config['number2'] != '' &&  $config['number2'] != 0){
                            $model = new Paidan();
                            $res = $model->change($row['shop_user_id'],$model::TYPE_VIDEO,$config['number2'],$row['id']);
                        }
                    }elseif ($userfind['pstatus'] == 1 && $userfind['level_id'] == 3){
                        if(isset($config['number3']) && $config['number3'] != '' &&  $config['number3'] != 0){
                            $model = new Paidan();
                            $res = $model->change($row['shop_user_id'],$model::TYPE_VIDEO,$config['number3'],$row['id']);
                        }
                    }elseif ($userfind['pstatus'] == 1 && $userfind['level_id'] == 4){
                        if(isset($config['number4']) && $config['number4'] != '' &&  $config['number4'] != 0){
                            $model = new Paidan();
                            $res = $model->change($row['shop_user_id'],$model::TYPE_VIDEO,$config['number4'],$row['id']);
                        }
                    }
                }
                if(isset($res) && !$res['status']){
                    $this->model->rollback();
                    $this->error($res['msg']);
                }else{
                    $this->model->commit();
                }

            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }
}